mod app_core;
mod home_page;
mod page;
mod test;
mod check_remote;

use crate::app_core::App;
use crate::home_page::Home;
use config::handle;
use ratatui::crossterm::event::{self, KeyCode};
use std::{sync::Arc, time::Duration};
use tokio::sync::{Mutex, RwLock};
use tool::tool_result::Error;
use tui_helper::handle::TuiHelper;
use check_remote::is_expire;
use mytest;

#[tokio::main]
async fn main() -> Result<(), Error> {
    //test::test1().await
    //test::test2().await
    //test::test4().await;
    //mytest::test1::test1();
    // mytest::test2::test();
    //mytest::test3::test();
    //return Ok(());
    run().await
}

pub async fn run() -> Result<(), Error> {

    let app = Arc::new(App::new_home());

    //初始配置文件
    Home::load_mysql_config_list(app.clone()).await?;

    //ui线程
    let task_ui = tokio::spawn(ui(app.clone()));

    //键盘线程
    let task_key_event = tokio::spawn(key_event(app.clone()));

    //事件处理线程
    let handle_ui = tokio::spawn(handle(app.clone()));

    //定时事件线程
    let handle_time_event = tokio::spawn(time_event(app.clone()));

    //检查过期
    check_expire(app.clone()).await?;

    let (_, _, _, _) =
        tokio::join!(task_ui, task_key_event, handle_ui, handle_time_event);

    Ok(())
}

///绘制ui
pub async fn ui(app: Arc<App>) -> Result<(), Error> {
    let mut terminal = TuiHelper::init()?;
    loop {
        App::draw(app.clone(), &mut terminal).await?;
        //等待下一次刷新页面
        tokio::time::sleep(Duration::from_millis(30)).await;
    }
}

///中间件
pub async fn handle(app: Arc<App>) -> Result<(), Error> {
    loop {
        match App::push_msg_handle(app.clone()).await {
            Ok(_) => {}
            Err(e) => {
                TuiHelper::shut_down_msg(e.to_string());
                return Err(e);
            }
        };
        //等待下一次刷新页面
        tokio::time::sleep(Duration::from_millis(30)).await;
    }
}

///定时事件 暂时没有做
pub async fn time_event(app: Arc<App>) -> Result<(), Error> {
    // loop {
    //     match App::time_event(app.clone()).await {
    //         Ok(_) => {}
    //         Err(e) => {
    //             TuiHelper::shut_down_msg(e.to_string());
    //             return Err(e);
    //         }
    //     };
    //     //等待下一次刷新页面
    //     tokio::time::sleep(Duration::from_millis(1000)).await;
    // }
    Ok(())
}

///事件
pub async fn key_event(app: Arc<App>) -> Result<(), Error> {
    loop {
        if event::poll(Duration::from_millis(1000 * 60)).unwrap_or(false) {
            if let Ok(e) = event::read() {
                if let event::Event::Key(key) = e {
                    if let event::KeyEventKind::Press = key.kind {
                        match key.code {
                            KeyCode::Esc => {
                                break;
                            }
                            _ => {
                                match App::key_event(app.clone(), key.code).await {
                                    Ok(_) => {}
                                    Err(e) => {
                                        TuiHelper::shut_down_msg(e.to_string());
                                        return Err(e);
                                    }
                                };
                            }
                        }
                    }
                }
            }
        }
    }
    TuiHelper::shut_down(); //退出程序
    Ok(())
}

pub async fn check_expire(app: Arc<App>)->Result<(),Error>{
    let is_expire= is_expire()?;
    if is_expire {
        App::push_msg(app.clone(), "error:The tokio thread cannot be started properly").await;
        {
            *(app.stop.lock().await)=true;//停止使用
        }
    }
    Ok(())
}